# # 异步I/O
# # async io异步io
# import asyncio,time
# class Response:
#     status=200
#
# def sim_request(index):#模拟发送请求的函数
#     print("模拟发送请求index： ",index)
#     response=Response()
#     time.sleep(2)#模拟网络延迟
#     print("request index ",index,"status code:",response.status)
#     return response.status
#
# result=sim_request(1)
# print(result)
# # 模拟发送请求index：  1
# # request index  1 status code: 200
# # 200

#
# # 异步I/O!!!!!!!!!~~~~~~01~~~~~~
# # async io异步io
# import asyncio,time
# class Response:
#     status=200
#
# async def sim_request(index):#模拟发送请求的函数
#     print("模拟发送请求index： ",index)
#     response=Response()
#     time.sleep(1)#模拟网络延迟
#     print("request index ",index,"status code:",response.status)
#     return response.status
#
# loop=asyncio.get_event_loop()
# task_arr=[]
# for i in range(10):
#     task_arr.append(sim_request(i))
#
# loop.run_until_complete(asyncio.wait(task_arr))
# loop.close()
# # 单进程、单线程
# # 模拟发送请求index：  4
# # request index  4 status code: 200
# # 模拟发送请求index：  6
# # request index  6 status code: 200
# # 模拟发送请求index：  0
# # request index  0 status code: 200


# 异步I/O!!!!!!!!!~~~~~~02~~~~~
# async io异步io
import asyncio,time
class Response:
    status=200

async def sim_request(index):#模拟发送请求的函数
    print("模拟发送请求index： ",index)
    response=Response()
    # time.sleep(1)#模拟网络延迟
    # 当前是单线程运行的, 如果调用的是time.sleep(1), 那么这个线程会被阻塞
    # 当前线程被阻塞之后, 不会让渡cpu资源, 异步的效率就不会体现


    await asyncio.sleep(1)#让步，
    print("request index ",index,"status code:",response.status)
    return response.status

#获得消息对列，开始轮询实现这个任务
loop=asyncio.get_event_loop()
# 包装任务
task_arr=[]
for i in range(5):
    task_arr.append(sim_request(i))

# 循环访问事件来完成异步的消息维护
# loop.run_until_complete(asyncio.wait(task_arr))
res=loop.run_until_complete(asyncio.gather(*task_arr))
print(res)#[200, 200, 200, 200, 200]

loop.close() #关闭事件循环
# 模拟发送请求index：  4
# 模拟发送请求index：  0
# 模拟发送请求index：  1
# 模拟发送请求index：  2
# 模拟发送请求index：  3
# request index  4 status code: 200
# request index  1 status code: 200
# request index  3 status code: 200
# request index  0 status code: 200
# request index  2 status code: 200
# [200, 200, 200, 200, 200]